/* 
 * File:   Server.h
 * Author: eoe2005
 *
 * Created on 2012年9月11日, 下午11:14
 */

#ifndef SERVER_H
#define	SERVER_H

#ifdef	__cplusplus
extern "C" {
#endif
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>    
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <dlfcn.h>

//listen port 
#define SERVER_PORT 8888
#define MAX_EVENTS 10

//read OR write
typedef struct __duilie__{
    char *chr;
    struct __duilie__ *next;
} S_DuiLie;
//
typedef struct __header{
    int uid;
    S_DuiLie r;
    S_DuiLie w;
    
} S_Header;
typedef struct __action{
    char *path;
    int isload;
    int (*func)(struct epoll_event ev);
}S_Action;
//Listen Tcp
int tcp_listen(const char *host,int port);
int tcp_read(struct epoll_event ev);
int tcp_write(struct epoll_event ev);
void setnonblocking(int sock);
S_Action * init_actions();





// INIT Actions
S_Action * init_actions(){
    void *handle;
    
    char * error;
    S_Action *action;
    action = malloc(sizeof(S_Action));
    action->path = "./action.so";
    handle = dlopen(action->path,RTLD_LAZY);
    error = dlerror();
    if(error){
        printf("Load:%s is %s\n",action->path,error);
        action->isload = 0;
    }else{
        action->func = dlsym(handle,"action");
        error = dlerror();
        if(error){
            printf("Load:%s is %s\n",action->path,error);
            action->isload = 0;
        }else{
            action->isload = 1;
        }
        
    }
    return action;
    
}
int tcp_listen(const char *host,int port){
    int fd;
    struct sockaddr_in server_addr;
    socklen_t server_addr_size;
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd == -1){
        exit(-1);
    }
    setnonblocking(fd);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(host);
    server_addr_size = sizeof(server_addr);
    if(bind(fd,(struct  sockaddr *)&server_addr,server_addr_size) == -1)
    {
        exit(-2);
    }
    if(listen(fd,5) == -1){
        exit(-3);
    }
    //exit(-9);
    return fd;
}
void setnonblocking(int sock){
     int opts;
     opts=fcntl(sock,F_GETFL);
     if(opts<0)
     {
          perror("fcntl(sock,GETFL)");
          exit(1);
     }
     opts = opts|O_NONBLOCK;
     if(fcntl(sock,F_SETFL,opts)<0)
     {
          perror("fcntl(sock,SETFL,opts)");
          exit(1);
     }  
}

//读取数据
int tcp_read(struct epoll_event ev){
}
//会写数据
int tcp_write(struct epoll_event ev){
}
#ifdef	__cplusplus
}
#endif

#endif	/* SERVER_H */

